Ext.onReady(function(){
    Ext.define('CourseschedulModel',{
        extend: 'Ext.data.Model',
        fields: [
			{name:'teacher_id',type:'string'},
			{name:'teacher_name',type:'string'},
			{name:'hour8'},
			{name:'hour9'},
			{name:'hour10'},
			{name:'hour11'},
			{name:'hour12'},
			{name:'hour13'},
			{name:'hour14'},
			{name:'hour15'},
			{name:'hour16'},
			{name:'hour17'},
			{name:'hour18'},
			{name:'hour19'},
			{name:'hour20'}
        ]
    });
    //创建数据源
    var CourseSchedulStore = Ext.create('Ext.data.Store', {
    	pageSize:20,
        model: 'CourseschedulModel',
	    proxy: {
	        type: 'ajax',
	        url: '/resourcecontrol/courseschedul_list/',
	        actionMethods:'post',
	        reader: {
	            type: 'json',
	            root: 'rows',
	            totalProperty: 'totalCount'
	        }
	    },
	    autoLoad: true
    });   

    //创建Grid
    var CourseSchedulGrid = Ext.create('Ext.grid.Panel',{
        store: CourseSchedulStore,
        //height: 500,
        selModel:Ext.create('Ext.selection.CheckboxModel'),
        columnLines:false,
        columns: [
            {text: "教师", width: 100, dataIndex: 'teacher_name',locked:true},
            {text: "8点", width: 100, dataIndex: 'hour8',renderer:rendererCourseSchedul},
            {text: "9点", width: 100, dataIndex: 'hour9',renderer:rendererCourseSchedul},
            {text: "10点", width: 100, dataIndex: 'hour10',renderer:rendererCourseSchedul},
            {text: "11点", width: 100, dataIndex: 'hour11',renderer:rendererCourseSchedul},
            {text: "12点", width: 100, dataIndex: 'hour12',renderer:rendererCourseSchedul},
            {text: "13点", width: 100, dataIndex: 'hour13',renderer:rendererCourseSchedul},
            {text: "14点", width: 100, dataIndex: 'hour14',renderer:rendererCourseSchedul},
            {text: "15点", width: 100, dataIndex: 'hour15',renderer:rendererCourseSchedul},
            {text: "16点", width: 100, dataIndex: 'hour16',renderer:rendererCourseSchedul},
            {text: "17点", width: 100, dataIndex: 'hour17',renderer:rendererCourseSchedul},
            {text: "18点", width: 100, dataIndex: 'hour18',renderer:rendererCourseSchedul},
            {text: "19点", width: 100, dataIndex: 'hour19',renderer:rendererCourseSchedul},
            {text: "20点", width: 100, dataIndex: 'hour20',renderer:rendererCourseSchedul}
        ],
        // disableSelection: false,
        layout : 'fit',
        loadMask:true,
        viewConfig: {
        	stripeRows: true,
            listeners: {
                itemdblclick: function(dataview, record, item, index, e) {
                    courseschedulWindow(record.get('teacher_id'),record.get('teacher_name'));
                }
            }
        },
        dockedItems : [{
            xtype : 'pagingtoolbar',
            store : CourseSchedulStore,
            dock : 'bottom',
            displayInfo : true,
            autoScroll:true 
        },{
        	dock:'top',
        	xtype:'toolbar',
        	items:[{
        		xtype:'button',
        		text:'<',
        		handler:function(){
        			var ct=Ext.getCmp('choicetime').getValue();
        			var ct_date=ct.getDate();
        			ct.setDate(ct_date-1);
        			Ext.getCmp('choicetime').setValue(ct);
        			var params = { choicetime: Ext.util.Format.dateRenderer('Y-m-d')(ct) };
        		    Ext.apply(CourseSchedulStore.proxy.extraParams, params);
        		   	CourseSchedulStore.load();					
        		}
        	},{
        		xtype:'button',
        		text:'今天',
        		handler:function(){
        			var ct=new Date();
        			Ext.getCmp('choicetime').setValue(ct);
        			var params = { choicetime: Ext.util.Format.dateRenderer('Y-m-d')(ct) };
        		    Ext.apply(CourseSchedulStore.proxy.extraParams, params);
        		   	CourseSchedulStore.load();	
        		}
        	},{
        		xtype:'button',
        		text:'>',
        		handler:function(){
        			var ct=Ext.getCmp('choicetime').getValue();
        			var ct_date=ct.getDate();
        			ct.setDate(ct_date+1);
        			Ext.getCmp('choicetime').setValue(ct);
        			var params = { choicetime: Ext.util.Format.dateRenderer('Y-m-d')(ct) };
        		    Ext.apply(CourseSchedulStore.proxy.extraParams, params);
        		   	CourseSchedulStore.load();	
        		}
        	},{
        		xtype:'datefield',
        		id:'choicetime',
        		name:'choicetime',
        		editable:false,
        		format: 'Y-m-d',
        		value: new Date()
        	},{
        		xtype:'button',
        		text:'查询',
        		iconCls:'search', 
        		handler:function(){
        			var ct=Ext.getCmp('choicetime').getValue();
        			var params = { choicetime: Ext.util.Format.dateRenderer('Y-m-d')(ct) };
        		    Ext.apply(CourseSchedulStore.proxy.extraParams, params);
        		    CourseSchedulStore.currentPage=1;
        		   	CourseSchedulStore.load();	
        		}
        	},'-',{
        		xtype:'button',
        		text:'排课',
        		iconCls:'edit', 
        		handler:function(){
        			var selected = CourseSchedulGrid.getSelectionModel().getSelection();
					if(selected[0]){
						Ext.getCmp('CourseSchedulForm').getForm().reset();
						courseschedulWindow(selected[0].data.teacher_id,selected[0].data.teacher_name);
					}else{
						Ext.Msg.alert('系统提示', '请选择需要排课的老师!');
					}
        		}
        	}]
        }]

    });
	//排课窗口
	function courseschedulWindow(teacherId,teacherName){
		Ext.getCmp('CourseSchedulForm').getForm().setValues({teacher_id:teacherId});
		TeacherDayGrid.setTitle("教师【"+teacherName+"】当日授课信息");
		var ct=Ext.getCmp('choicetime').getValue();
		var params = { teacher_id: teacherId, choicetime: Ext.util.Format.dateRenderer('Y-m-d')(ct)};
	    Ext.apply(TeacherDayStore.proxy.extraParams, params);
	    TeacherDayStore.load();	
		win.show();		
	}
    //渲染返回排课信息
    function rendererCourseSchedul(value, metaData, record, rowIdx, colIdx, store, view){
    	var results="";
    	if(value.length>0){
    		metaData.style='background:#FF66CC';
        	for(var i=0;i<value.length;i++){
        		results+=value[i].student_name+" ";
        	}    		
    	}
    	return results;
    }
    
	//教师课程
    Ext.define('TeacherDayModel', {
        extend: 'Ext.data.Model',
        fields: [
            {name:'id',type:'string'},
            {name:'student_id',type:'string'},
            {name:'student_name',type:'string'},
            {name:'start_time',type:'string'},
            {name:'end_time',type:'string'},
            {name:'grade_name',type:'string'},
            {name:'course_name',type:'string'}
        ]
    });
    var TeacherDayStore = Ext.create('Ext.data.JsonStore', {
        model: 'TeacherDayModel',
	    proxy: {
	        type: 'ajax',
	        url: '/resourcecontrol/teacher_day_course/',
	        actionMethods:'post',
	        reader: {
	            type: 'json',
	            root: 'rows',
	            totalProperty: 'totalCount'
	        }
	    }
    });

    var TeacherDayGrid = Ext.create('Ext.grid.Panel', {
        store: TeacherDayStore,
        //selModel:Ext.create('Ext.selection.CheckboxModel'),
        width:530,
        region:'west',
        loadMask:true,
        height:150,
        viewConfig: {
            stripeRows: true
        },
        columns: [
        	Ext.create('Ext.grid.RowNumberer'),
            {text: "学生姓名", dataIndex: 'student_name'},
            {text: "年级", dataIndex: 'grade_name'},
            {text: "课程", dataIndex: 'course_name'},
            {text: "上课时间", dataIndex: 'start_time'},
            {text: "下课时间", dataIndex: 'end_time'}
        ]
    });
    
    
	var CourseSchedulPanel = Ext.create('Ext.panel.Panel', {
	    layout: {
	        type: 'border'
	    },
	    items:[TeacherDayGrid,{
	    	id:'CourseSchedulForm',
            xtype: 'form',
            bodyPadding: 10,
    		split:true,
    		region:'center',
            fieldDefaults: {
                labelAlign: 'right',
                labelWidth: 60,
                msgTarget: 'side'
            },
            items: [{
    			xtype:'hiddenfield',
    			id:'teacher_id',
    			name:'teacher_id'
    		},{
            	xtype:'combobox',
            	anchor: '100%',
            	fieldLabel:'学生',
            	name:'student_id',
            	editable:true,
            	valueField:'id',
            	displayField:'name',
            	typeAhead:true,
            	minChars:1,
            	allowBlank: false,
            	store: new Ext.data.Store({
//            		pageSize:20,
            		singleton : true, 
            		proxy: {
            			type: 'ajax',
            			url: '/customercontrol/contract_student_select/',
            			actionMethods:'post',
            			reader: {
            				type: 'json'
            			}
            		},
            		fields:['id', 'name'], 
            		autoLoad:true 
            	}),
            	listConfig: {
            		loadingText: '正在查找...',
            		emptyText: '没有找到匹配值.'
            	},	        
//            	pageSize: 20,
            	listeners: {
            		'select': function(combo, records, opts) {	
            			var studentCourseHourCombox=Ext.getCmp('CourseSchedulForm').getForm().findField('studentCourseHour');
            			var params = { student_id:records[0].data.id};
	    				Ext.apply(studentCourseHourCombox.getStore().proxy.extraParams, params);	
            		}
            	}	        
            },{
				xtype:'combobox',
				fieldLabel:'课程',
				anchor: '100%',
				name:'studentCourseHour',
				editable:false,
				forceSelection: true, 
				displayField:'course_name',
				listConfig: {
					getInnerTpl: function() {
						return '<div data-qtip="{grade_id}.{grade_name}.{course_id}.{course_name}.{course_times}.{study_type_id}.{study_type}">{course_name}({grade})[{course_times}]<{study_type}></div>';
					}
				},			
				store: new Ext.data.Store({ 
					proxy: {
						type: 'ajax',
						url: '/resourcecontrol/student_course_hour/',
						actionMethods:'post',
						reader: {
							type: 'json',
							root: 'message'
						}
					},
					fields:['course_name', 'course_times','study_type','grade_name','grade_id','course_id','study_type_id']
				}),
				listeners: {  
					beforequery:function(queryEvent,eOpts){
						queryEvent.combo.getStore().load();
					} 
				}			    
			},{
            	xtype: 'timefield',
            	fieldLabel:'上课时间',
            	name: 'starttime',
            	minValue: '8:00',
            	maxValue: '22:00',
            	format:'H:i',
            	increment: 15,
            	allowBlank: false,
            	anchor: '100%'
            },{
            	xtype: 'timefield',
            	fieldLabel:'下课时间',
            	name: 'endtime',
            	minValue: '8:00',
            	maxValue: '22:00',
            	format:'H:i',
            	increment: 15,
            	allowBlank: false,
            	anchor: '100%'
            },{
            	xtype: 'container',
            	style: 'text-align:center',
            	items: [{
            		xtype: 'button',
            		cls: 'contactBtn',
            		//scale: 'large',
            		text: '确认排课',
            		handler: function(){
						var studentCourseHourCombox=Ext.getCmp('CourseSchedulForm').getForm().findField('studentCourseHour');
						var schcData=studentCourseHourCombox.displayTplData[0];
						var schedule_time=(Ext.getCmp('CourseSchedulForm').getForm().findField('endtime').getValue()-Ext.getCmp('CourseSchedulForm').getForm().findField('starttime').getValue())/3600000;
						if(schedule_time<0 ||schedule_time>schcData.course_times){
							Ext.Msg.alert('系统提示', '排课时间不正确或超出剩余课时!');
							return;
						}
            			var ct=Ext.getCmp('choicetime').getValue();
            			var teacherId = Ext.getCmp('teacher_id').getValue();
            			form=Ext.getCmp('CourseSchedulForm');
            			if (form.getForm().isValid()) {
            				form.getForm().submit({
            					waitTitle : '请稍候',
            					waitMsg : '正在处理......',
            					url : '/resourcecontrol/courseschedul_save/',
            					params:{
            						teacher_id: teacherId,
            						grade_id:schcData.grade_id,
            						course_id:schcData.course_id,
            						study_type_id:schcData.study_type_id,
            						choicetime: Ext.util.Format.dateRenderer('Y-m-d')(ct)
            					},
            					success : function(form, action) {
            						var params = { teacher_id: teacherId, choicetime: Ext.util.Format.dateRenderer('Y-m-d')(ct)};
            					    Ext.apply(TeacherDayStore.proxy.extraParams, params);
            					    TeacherDayStore.load();	
            					},
            					failure : function(form, action) {
            						if (action.result) {
            							Ext.Msg.alert('系统提示', action.result.message);
            						} 
            					}
            				});
            			}            			
            		}
            	},{
            		xtype: 'button',
            		cls: 'contactBtn',
            		text: '删除排课',
            		handler: function(){
            			var selected = TeacherDayGrid.getSelectionModel().getSelection();
            			Ext.Ajax.request({
            			    url:'/resourcecontrol/courseschedul_del/',
            			    method : 'post',
            			    params:{
            			    	id:selected[0].data.id
            			    },
            			    success:function(response){
            			        var results =  Ext.decode(response.responseText);
            			        if(results.success){
            			        	TeacherDayStore.load();
            			        }else{
            			        	Ext.Msg.alert('系统提示', results.message);
            			        }
            			    }
            			});
            		}
            	}]
            }]
        }]
	});
    

	var win = Ext.create('Ext.window.Window', {
	    height: 400,
	    width: 800,
	    layout: {
	        type: 'fit'
	    },
		modal: true,
		closeAction: 'hide',
		items : [CourseSchedulPanel],
		//closable : false,
		resizable : false,
		buttonAlign : 'center',
		buttons : [{
			text : '排课完成',
			handler : function() {
				Ext.getCmp('CourseSchedulForm').getForm().reset();
				win.hide();
    			var params = { choicetime: Ext.util.Format.dateRenderer('Y-m-d')(Ext.getCmp('choicetime').getValue()) };
    		    Ext.apply(CourseSchedulStore.proxy.extraParams, params);
    		   	CourseSchedulStore.load();					
			}
		} ]
	});  	
  
	Ext.create('Ext.container.Viewport',{
		layout:'fit',
		renderTo: 'courseschedul-grid',
		items:[CourseSchedulGrid]
	});    
});